/**
 * 路由全局拦截器
 */

import router from '../router'
import {asyncRoute, constantRouter} from '@/router'
import {getToken} from '@/utils/token'
import store from '@/store'
import {getLoginUserInfo, getDict as getdict_, getMenus as getMenu_} from '@/api/login'
import {userPermissions} from '@/utils/auth'

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  if (getToken()) { // 已经登录
    // if (to.path === '/login') {
    //   next({path: '/'})
    // } else {
    //   next()
    // }
    // if (store.getters.menu.length === 0) {
    // console.log(store.getters.vuexStore, 'in vuex')
    if (!store.getters.vuexStore) {
      /* 获取用户信息 */

      // 获取字典信息
      getdict_().then(res => {
        store.dispatch('setDict', res.data);
      });

      // 获取用户信息
      getLoginUserInfo().then(res => {
        store.dispatch('setUserinfo', res.data);
      });

      // 获取菜单及权限
      getMenu_().then(res => {
        store.dispatch('setMenu', res.data);
        store.dispatch('setVuexStoreToTrue');

        userPermissions(res.data);
        // let ml = getMenuList(res.data);
        // console.log(asyncRoute);
        let route = dynamicRouter(res.data);
        router.options.routes[0].children = [...route, ...constantRouter];
        router.addRoutes(router.options.routes);
        // next();
        next({ ...to, replace: true }); // 确保从后台加载完菜单数据
      });
    } else {
      next();
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next({path: '/login'})
    }
  }
})

/**
 * 动态生成路由
 */
function dynamicRouter (menus) {
  let menuList = getMenuList(menus);
  let routeArr = [];
  asyncRoute.forEach((route) => {
    menuList.forEach((menu) => {
      if (route.path === menu.router) {
        if (!route.meta) {
          route.meta = {title: menu.authName};
        }
        routeArr.push(route);
      }
    });
  });
  return routeArr;
}

function getMenuList (menus) {
  const menuList = [];
  Array.from(menus).forEach(function (record) {
    if (parseInt(record.type) === 0) {
      menuList.push(record);
      if (record.children && record.children.length > 0) {
        let child = getMenuList(record.children);
        menuList.push(...child);
      }
    }
  });
  return menuList;
}
